package de.tabuma.ssoclient.logik;

import de.tabuma.ssoclient.entity.*;
import java.util.*;

/**
 *
 * @author alefen
 */
public class AttributeHashFacade {
    private static Hashtable<String,List<Attribute>> hash = new Hashtable<String,List<Attribute>>();

    public synchronized static void put(Attribute attribute, String ssoId) {
        List<Attribute> hashList = hash.get(ssoId+"_"+attribute.getUserId());
        if(hashList==null) {
            hashList = new ArrayList<Attribute>();
        }
        boolean add = false;
        for(int i=0;i<hashList.size();i++) {
            Attribute listAttribute = hashList.get(i);
            if(attribute.getId().intValue()==listAttribute.getId().intValue()) {
                hashList.set(i, attribute);
                i = hashList.size();
                add = true;
            }
        }

        if(!add) {
            hashList.add(attribute);
        }
        hash.put(ssoId+attribute.getUserId(), hashList);
    }

    public synchronized static void remove(int id, String ssoId) {
        Enumeration<String> sessionId = hash.keys();
        while(sessionId.hasMoreElements()) {
            String session = sessionId.nextElement();
            if(session.indexOf(ssoId)!=-1) {
                List<Attribute> hashList = hash.get(session);
                for(int i=0;i<hashList.size();i++) {
                    Attribute attribute = hashList.get(i);
                    if(attribute.getId().intValue()==id) {
                        hashList.remove(i);
                        hash.put(session, hashList);
                        return;
                    }
                }

            }
        }
    }

    public synchronized static Attribute get(int id, String ssoId) {
        Enumeration<String> sessionId = hash.keys();
        while(sessionId.hasMoreElements()) {
            String session = sessionId.nextElement();
            if(session.indexOf(ssoId)!=-1) {
                List<Attribute> hashList = hash.get(session);
                for(int i=0;i<hashList.size();i++) {
                    Attribute attribute = hashList.get(i);
                    if(attribute.getId().intValue()==id) {
                        return attribute;
                    }
                }

            }
        }
        return null;
    }

    public static synchronized void addList(String ssoId, int userId, List<Attribute> aList) {
        hash.put(ssoId+"_"+userId, aList);
    }

    public static synchronized void addList(String ssoId, List<Attribute> aList) {
        hash.put(ssoId, aList);
    }

    public static synchronized List<Attribute> getList(String ssoId) {
        return hash.get(ssoId);
    }

    public static synchronized List<Attribute> getList(int user, String ssoId) {
        return hash.get(ssoId+"_"+user);
    }
}
